import api from "../common/api";
import { getData, resetData } from "../models/transferData";
import { cooperationBehavior } from "./cooperation";
import constant from "../common/constant";
import { gioSendAuthLog } from "../common/gioHandler"
import { userInfoBehavior } from "./userInfo";

const app = getApp();
export const imBe = Behavior({
  behaviors: [cooperationBehavior, userInfoBehavior],
  data: {
    firstMsg: true, //打开聊天的第一条发送消息
    hiMsg: "Hi，我对您这套房源非常感兴趣，期待进一步沟通！",
    singleCount: 10, //单页聊天数据条数
    conversationID: null,
    cooperationId: "", //合作房源id
    targetUserID: "", // 对方id
    ispop: "", // 是否弹出授权框
    entryType: "2", // 入口渠道：1:IM 2:外呼手机号
    agentId: "", //对方id（房源方）
  },
  /**
   * 1. 首先自己需要授权且登录ok
   * 2. 判断对方是否是合法im账号
   * 2.5  获取历史聊天记录查找是否有本次合作的卡片。。。。
   * 3. 发送本次合作的房源卡片
   * 4. 发送授权卡片信息（需要判断条件是否满足）
   *
   */
  methods: {
    $sendAuthCard(options) {
      // debugger
      this.data.cooperationId = options.cooperationId;
      this.data.targetUserID = options.unionid;
      this.data.agentId = options.agentId;
      this.data.ispop = options.ispop;

      /** 认证小卡片信息 */
      let authCardInfo = getData("authCardInfo");
      resetData("authCardInfo");

      app.globalData.loginPromise
        .then(({ sessionUser }) => {
          return this.$mineValid(sessionUser);
        })
        .then((sessionUser) => {
          const { wechatUnionid } = sessionUser.extProps;
          return this.$targetUserVerify(wechatUnionid, this.data.targetUserID);
        })
        .then(() => {
          return this.$initMessage(this.data.targetUserID);
        })
        .then((list) => {
          this.$houseCardManage(list, this.data.targetUserID, this.data.cooperationId).then(() => {
            setTimeout(() => {
              authCardInfo && this.$authCardManage(list, this.data.targetUserID, authCardInfo);
            }, 1000);
          });
        });
    },

    // 校验账号是否合法
    $mineValid(sessionUser, cb) {
      const { wechatUnionid, wxMobile } = sessionUser.extProps;
      if (!wechatUnionid || !(wxMobile > 0)) {
        wx.showModal({
          content: !wechatUnionid
            ? "您当前还未授权基本信息，不能使用该功能！"
            : "您当前还未授权手机号，不能使用该功能！",
          showCancel: false,
          confirmText: "我知道了",
          success(res) {
            cb && cb();
          },
        });
        return Promise.reject();
      }

      return Promise.resolve(sessionUser);
    },

    // 保证已im登录的前提下校验对法账号是否合法
    $targetUserVerify(id, targetUserID, cb) {
      return app.timControl
        .sdkReadyAndNext(id)
        .then(() => {
          return app.timControl.getUserProfile([targetUserID]);
        })
        .then((res) => {
          if (!res || res.length === 0) {
            wx.showModal({
              content: "对方账户不存在！",
              showCancel: false,
              confirmText: "我知道了",
              success(res) {
                cb && cb();
              },
            });
            return Promise.reject();
          }
        });
    },

    // 获取会话id
    $getConversationList(userid) {
      return app.timControl.getConversationList().then((imResponse) => {
        let csList = imResponse.data.conversationList;
        let conversationItem = csList.find((v) => v.userProfile.userID == userid);

        return conversationItem ? Promise.resolve(conversationItem.conversationID) : Promise.reject();
      });
    },

    // 查看与跟对方是否有历史会话记录
    $initMessage(targetUserID) {
      return this.$getConversationList(targetUserID)
        .then((id) => {
          return this.$getMessageList(id);
        })
        .catch((v) => {
          return Promise.resolve([]);
        });
    },

    // 通过历史会话id获取历史聊天记录
    $getMessageList(conversationID) {
      return app.timControl
        .getMessageList({
          conversationID, //会话列表传递过来的参数
          count: this.data.singleCount,
        })
        .then(({ data }) => {
          return Promise.resolve(data.messageList);
        });
    },

    // 发送该房源卡片信息
    $houseCardManage(list, targetUserID, cooperationId, ignoreRepeat=false, cardType) {
      // 没有就此房源发生过聊天
      if (!ignoreRepeat && this.$findHouseCard(list, cooperationId)) {
        return Promise.resolve()
      }
      return this.getInfoByCooperationId(cooperationId).then((content) => {
        // 已下架
        if (content.hmCooperationDelVO.cooperationDown) {
          wx.showToast({ icon: "none", title: "该房源已下架~" });
          return Promise.resolve();
        }
        
        // 房源是对方的才需要以此房源插入一条沟通信息
        if (targetUserID === content.jjrVO.wechatUnionid) {
          api.insertHmCooperationTalkingMain({
            delId: content.hmCooperationDelVO.delId,
            cooperationId,
            houseOwnerId: content.jjrVO.id,
            houseOwnerUnionid: content.jjrVO.wechatUnionid,
            haveCommunicateType: "IM",
          });
        }

        return this.$sendHouseCard(targetUserID, cooperationId, cardType);
      });
    },

    $findHouseCard(list, cooperationId) {
      let targetItem = list.find((item) => {
        if (item.payload.data == "card_house" && item.payload.cooperationId == cooperationId) {
          return true;
        }
      });
      return !!targetItem;
    },

    // 发送房源信息卡片
    $sendHouseCard(targetUserID, cooperationId, cardType) {
      let message = app.timControl.createCustomMessage(targetUserID, {
        data: cardType || "card_house",
        description: "request",
        extension: JSON.stringify({ cooperationId, }),
      });
      return this.imSendMessage(message);
    },

    // 公众号提醒
    $gzhMessageHandler({ time, payload }) {
      let isAuth = payload.data === 'auth_card'
      if (this.data.firstMsg || isAuth) {
        this.data.firstMsg = false;
        api.sendGZHMessage({
          unionId: this.data.targetUserID,
          talkingTime: time,
          type: isAuth ? 'auth' : 'primary'
        });
        wx.gio("track", constant.sendWeChatInform, {
          [constant.InFromType]: isAuth? 'IM未读-认证消息':'IM未读-普通消息',
        });
      }
    },

    $authCardManage(list, targetUserID, authCardInfo) {
      // 弹了授权弹层则必定发送小卡片
      if (this.data.ispop === "1") {
        this._sendAuthCard(targetUserID, list, authCardInfo);

        // 调用接口判断是否发送小卡片
      } else if (this.data.ispop === "0") {
        api.checkIMCard({ toUserId: this.data.agentId, entryType: this.data.entryType }, ({ data }) => {
          const content = data.content;
          if (content && content.needCard == "1") {
            this._sendAuthCard(targetUserID, list, authCardInfo);
          }
        });
      }
    },

    _sendAuthCard(targetUserID, list, authCardInfo) {
      let p = Promise.resolve();
      let hasHiMsg = list.find((item) => item.type === "TIMTextElem" && item.payload.text === this.data.hiMsg);
      if (!hasHiMsg) {
        let message = app.timControl.createTextMessage(targetUserID, this.data.hiMsg);
        p = this.imSendMessage(message);
      }
      p.then(() => {
        let message = app.timControl.createCustomMessage(targetUserID, {
          data: "auth_card",
          description: "request",
          extension: JSON.stringify(authCardInfo),
        });
        setTimeout(() => {
          this.imSendMessage(message);
          this.getAuthenticatedInfoByUnionid(targetUserID).then(({ mobile, nick}) => {
            gioSendAuthLog(constant.send_IM_inform, mobile, nick)
          });
        }, 1000);
      });
    },

    // 发送消息
    imSendMessage(message) {
      return app.timControl
        .sendMessage(message)
        .then(({ data }) => {
          let message = data.message;
          this.$gzhMessageHandler(message);
        })
        .catch((imError) => {
          console.error("发送消息sendMessage", imError);
        });
    },
  },
});
